<?php

class Infopages extends CActiveRecord
{
	public $menu_link;
	
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return '{{infopages}}';
	}

	public function rules()
	{
		$languages = Languages::model()->getLanguageCodes();
		
		$required = 'active';
		foreach ($languages as $lang)
		{
			$required .= ', title_'.$lang.', body_'.$lang;
		}
		$length = '';
		foreach ($languages as $lang)
		{
			$length .= 'title_'.$lang.',';
		}
		$length = rtrim($length, ',');
		$search = 'id, active, sorter, date_updated';
		foreach ($languages as $lang)
		{
			$search .= ', title_'.$lang.', body_'.$lang;
		}
		return array(
			array($required, 'required'),
			array('active, sorter', 'numerical', 'integerOnly'=>true),
			array($length, 'length', 'max'=>255),
			array($search, 'safe', 'on'=>'search'),
		);
	}

	public function relations()
	{
		return array(
		);
	}

	public function attributeLabels()
	{
		$languages = Languages::model()->getLanguageCodes();
		
		$labels = array(
			'id' => 'ID',
			'active' => tt('Active'),
			'sorter' => tt('Sorter'),
			'menu_link' => tt('Menu Link'),
		);
		foreach($languages as $lang)
		{
			$labels['title_'.$lang] = tt('Title');
			$labels['body_'.$lang] = tt('Body');
		}
		
		return $labels;
	}

	public function search()
	{
		$criteria=new CDbCriteria;

		$languages = Languages::model()->getLanguageCodes();
		foreach ($languages as $lang)
		{
			$criteria->compare('title_'.$lang,$this->{'title_'.$lang},true);
			$criteria->compare('body_'.$lang,$this->{'body_'.$lang},true);
		}
		$criteria->order = 'sorter ASC';

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>param('adminPaginationPageSize', 20),
			),
		));
	}
	
	public function behaviors()
	{
		return array(
			'AutoTimestampBehavior' => array(
				'class' => 'zii.behaviors.CTimestampBehavior',
				'createAttribute' => null,
				'updateAttribute' => 'date_updated',
			),
		);
	}

	public function beforeSave()
	{
		if($this->isNewRecord)
		{
			$this->active = 1;

			$maxSorter = Yii::app()->db->createCommand()
				->select('MAX(sorter) as maxSorter')
				->from('{{infopages}}')
				->queryRow();
			$this->sorter = $maxSorter['maxSorter']+1;
		}
	
		return parent::beforeSave();
	}
}